"""
共享充电宝数据仓库 - AI智能分析服务
基于DeepSeek API提供数据分析和可视化功能
"""

import os
import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
import seaborn as sns
from flask import Flask, jsonify, request
from flask_cors import CORS
from openai import OpenAI
import json
import io
import base64
from datetime import datetime
import warnings
warnings.filterwarnings('ignore')

# 设置中文字体
plt.rcParams['font.sans-serif'] = ['SimHei', 'Microsoft YaHei']
plt.rcParams['axes.unicode_minus'] = False

app = Flask(__name__)
CORS(app)

# DeepSeek API配置
DEEPSEEK_API_KEY = "sk-75c0f34904d14575827d5553acadbd52"
DEEPSEEK_BASE_URL = "https://api.deepseek.com"

client = OpenAI(api_key=DEEPSEEK_API_KEY, base_url=DEEPSEEK_BASE_URL)

# 数据路径配置
DATA_PATH = os.path.join(os.path.dirname(__file__), '..', 'data', 'cleaned_data')

class DataAnalysisService:
    """数据分析服务类"""

    def __init__(self):
        self.load_data()

    def load_data(self):
        """加载所有CSV数据"""
        try:
            self.order_data = pd.read_csv(os.path.join(DATA_PATH, 'order_table.csv'))
            self.user_data = pd.read_csv(os.path.join(DATA_PATH, 'user_table.csv'))
            self.region_data = pd.read_csv(os.path.join(DATA_PATH, 'region_table.csv'))
            self.time_data = pd.read_csv(os.path.join(DATA_PATH, 'time_table.csv'))
            print("✅ 数据加载成功")
        except Exception as e:
            print(f"❌ 数据加载失败: {e}")
            # 创建空的DataFrame作为备用
            self.order_data = pd.DataFrame()
            self.user_data = pd.DataFrame()
            self.region_data = pd.DataFrame()
            self.time_data = pd.DataFrame()

    def get_data_summary(self):
        """获取数据概览"""
        return {
            'order_count': len(self.order_data),
            'user_count': len(self.user_data),
            'region_count': len(self.region_data),
            'time_range': len(self.time_data),
            'brands': self.order_data['品牌'].nunique() if not self.order_data.empty else 0,
            'avg_price': round(self.order_data['单价'].mean(), 2) if not self.order_data.empty else 0
        }

class AIAnalysisService:
    """AI分析服务类"""

    def __init__(self, data_service):
        self.data_service = data_service

    def call_deepseek_api(self, prompt, context=""):
        """调用DeepSeek API"""
        try:
            system_prompt = f"""你是一个专业的数据分析师，专门分析共享充电宝业务数据。

数据背景：
{context}

请基于提供的数据进行深入分析，提供有价值的商业洞察和建议。
回答要求：
1. 使用中文回答
2. 分析要专业、准确
3. 提供具体的数字支撑
4. 给出可执行的建议
5. 保持简洁明了"""

            response = client.chat.completions.create(
                model="deepseek-chat",
                messages=[
                    {"role": "system", "content": system_prompt},
                    {"role": "user", "content": prompt}
                ],
                temperature=0.7,
                max_tokens=1500,
                stream=False
            )

            return response.choices[0].message.content

        except Exception as e:
            return f"AI分析服务暂时不可用: {str(e)}"

    def analyze_user_behavior(self):
        """用户行为分析"""
        try:
            if self.data_service.user_data.empty or self.data_service.order_data.empty:
                return "数据不足，无法进行用户行为分析"

            # 用户统计
            user_stats = {
                "总用户数": len(self.data_service.user_data),
                "平均年龄": round(self.data_service.user_data['年龄'].mean(), 1),
                "性别分布": self.data_service.user_data['性别'].value_counts().to_dict(),
                "职业分布TOP5": self.data_service.user_data['职业'].value_counts().head(5).to_dict()
            }

            # 订单统计
            order_stats = {
                "总订单数": len(self.data_service.order_data),
                "平均单价": round(self.data_service.order_data['单价'].mean(), 2),
                "品牌偏好": self.data_service.order_data['品牌'].value_counts().head(3).to_dict()
            }

            context = f"""
用户数据统计: {json.dumps(user_stats, ensure_ascii=False)}
订单数据统计: {json.dumps(order_stats, ensure_ascii=False)}
"""

            prompt = "请分析共享充电宝用户的行为特征，包括用户画像、使用偏好、消费习惯等，并提供运营建议。"

            return self.call_deepseek_api(prompt, context)

        except Exception as e:
            return f"用户行为分析失败: {str(e)}"

    def analyze_market_trend(self):
        """市场趋势分析"""
        try:
            if self.data_service.order_data.empty:
                return "数据不足，无法进行市场趋势分析"

            # 品牌市场份额
            brand_share = self.data_service.order_data['品牌'].value_counts()
            brand_percentage = (brand_share / len(self.data_service.order_data) * 100).round(2)

            # 价格分析
            price_stats = {
                "平均单价": round(self.data_service.order_data['单价'].mean(), 2),
                "价格分布": self.data_service.order_data['单价'].value_counts().to_dict(),
                "最高单价": self.data_service.order_data['单价'].max(),
                "最低单价": self.data_service.order_data['单价'].min()
            }

            context = f"""
品牌市场份额: {brand_share.to_dict()}
品牌占比: {brand_percentage.to_dict()}
价格统计: {json.dumps(price_stats, ensure_ascii=False)}
"""

            prompt = "请分析共享充电宝市场趋势，包括品牌竞争格局、价格策略、市场发展方向等，并预测未来趋势。"

            return self.call_deepseek_api(prompt, context)

        except Exception as e:
            return f"市场趋势分析失败: {str(e)}"

    def analyze_regional_distribution(self):
        """区域分布分析"""
        try:
            if self.data_service.region_data.empty or self.data_service.order_data.empty:
                return "数据不足，无法进行区域分析"

            # 省份分布
            province_stats = self.data_service.region_data['省份'].value_counts().head(10)

            # 城市分布
            city_stats = self.data_service.region_data['城市'].value_counts().head(10)

            context = f"""
省份分布TOP10: {province_stats.to_dict()}
城市分布TOP10: {city_stats.to_dict()}
总地区数: {len(self.data_service.region_data)}
"""

            prompt = "请分析共享充电宝的区域分布特征，包括地域偏好、城市渗透率、区域发展潜力等，并提供区域扩张建议。"

            return self.call_deepseek_api(prompt, context)

        except Exception as e:
            return f"区域分布分析失败: {str(e)}"

    def analyze_revenue_optimization(self):
        """收入优化分析"""
        try:
            if self.data_service.order_data.empty:
                return "数据不足，无法进行收入分析"

            # 收入统计
            total_revenue = (self.data_service.order_data['单价'].sum())
            avg_revenue_per_order = round(self.data_service.order_data['单价'].mean(), 2)

            # 品牌收入分析
            brand_revenue = self.data_service.order_data.groupby('品牌')['单价'].agg(['sum', 'mean', 'count'])

            context = f"""
总收入: {total_revenue}元
平均订单收入: {avg_revenue_per_order}元
品牌收入分析: {brand_revenue.to_dict()}
"""

            prompt = "请分析共享充电宝的收入优化策略，包括定价策略、品牌效益、收入增长点等，并提供具体的优化建议。"

            return self.call_deepseek_api(prompt, context)

        except Exception as e:
            return f"收入优化分析失败: {str(e)}"

    def chat_analysis(self, question):
        """智能问答分析"""
        try:
            # 获取数据概览作为上下文
            data_summary = self.data_service.get_data_summary()

            context = f"""
当前数据概览:
- 订单总数: {data_summary['order_count']}
- 用户总数: {data_summary['user_count']}
- 覆盖地区: {data_summary['region_count']}
- 品牌数量: {data_summary['brands']}
- 平均单价: {data_summary['avg_price']}元
"""

            return self.call_deepseek_api(question, context)

        except Exception as e:
            return f"智能问答失败: {str(e)}"

class VisualizationService:
    """数据可视化服务类"""

    def __init__(self, data_service):
        self.data_service = data_service

    def plot_to_base64(self, fig):
        """将matplotlib图表转换为base64字符串"""
        img_buffer = io.BytesIO()
        fig.savefig(img_buffer, format='png', dpi=150, bbox_inches='tight',
                   facecolor='white', edgecolor='none')
        img_buffer.seek(0)
        img_str = base64.b64encode(img_buffer.getvalue()).decode()
        plt.close(fig)
        return f"data:image/png;base64,{img_str}"

    def create_brand_analysis_chart(self):
        """创建品牌分析图表"""
        try:
            if self.data_service.order_data.empty:
                return None

            fig, ((ax1, ax2), (ax3, ax4)) = plt.subplots(2, 2, figsize=(15, 12))
            fig.suptitle('共享充电宝品牌分析', fontsize=16, fontweight='bold')

            # 品牌订单数量
            brand_counts = self.data_service.order_data['品牌'].value_counts()
            ax1.pie(brand_counts.values, labels=brand_counts.index, autopct='%1.1f%%', startangle=90)
            ax1.set_title('品牌市场份额')

            # 品牌平均单价
            brand_price = self.data_service.order_data.groupby('品牌')['单价'].mean().sort_values(ascending=False)
            ax2.bar(brand_price.index, brand_price.values, color='skyblue')
            ax2.set_title('品牌平均单价')
            ax2.set_ylabel('单价(元)')
            plt.setp(ax2.xaxis.get_majorticklabels(), rotation=45)

            # 品牌收入分析
            brand_revenue = self.data_service.order_data.groupby('品牌')['单价'].sum().sort_values(ascending=False)
            ax3.bar(brand_revenue.index, brand_revenue.values, color='lightgreen')
            ax3.set_title('品牌总收入')
            ax3.set_ylabel('收入(元)')
            plt.setp(ax3.xaxis.get_majorticklabels(), rotation=45)

            # 单价分布
            ax4.hist(self.data_service.order_data['单价'], bins=10, color='orange', alpha=0.7)
            ax4.set_title('单价分布')
            ax4.set_xlabel('单价(元)')
            ax4.set_ylabel('订单数量')

            plt.tight_layout()
            return self.plot_to_base64(fig)

        except Exception as e:
            print(f"品牌分析图表生成失败: {e}")
            return None

    def create_user_analysis_chart(self):
        """创建用户分析图表"""
        try:
            if self.data_service.user_data.empty:
                return None

            fig, ((ax1, ax2), (ax3, ax4)) = plt.subplots(2, 2, figsize=(15, 12))
            fig.suptitle('用户行为分析', fontsize=16, fontweight='bold')

            # 年龄分布
            age_bins = [0, 20, 30, 40, 50, 60, 100]
            age_labels = ['<20', '20-30', '30-40', '40-50', '50-60', '60+']
            age_groups = pd.cut(self.data_service.user_data['年龄'], bins=age_bins, labels=age_labels)
            age_counts = age_groups.value_counts()
            ax1.bar(age_counts.index, age_counts.values, color='lightblue')
            ax1.set_title('用户年龄分布')
            ax1.set_ylabel('用户数量')

            # 性别分布
            gender_counts = self.data_service.user_data['性别'].value_counts()
            ax2.pie(gender_counts.values, labels=gender_counts.index, autopct='%1.1f%%', startangle=90)
            ax2.set_title('用户性别分布')

            # 职业分布TOP10
            job_counts = self.data_service.user_data['职业'].value_counts().head(10)
            ax3.barh(job_counts.index, job_counts.values, color='lightgreen')
            ax3.set_title('用户职业分布TOP10')
            ax3.set_xlabel('用户数量')

            # 地址省份分布TOP10
            province_counts = self.data_service.user_data['地址'].str.extract(r'(\w+省|\w+市|\w+自治区)')[0].value_counts().head(10)
            ax4.bar(province_counts.index, province_counts.values, color='orange')
            ax4.set_title('用户地域分布TOP10')
            ax4.set_ylabel('用户数量')
            plt.setp(ax4.xaxis.get_majorticklabels(), rotation=45)

            plt.tight_layout()
            return self.plot_to_base64(fig)

        except Exception as e:
            print(f"用户分析图表生成失败: {e}")
            return None

    def create_region_analysis_chart(self):
        """创建地区分析图表"""
        try:
            if self.data_service.region_data.empty:
                return None

            fig, ((ax1, ax2), (ax3, ax4)) = plt.subplots(2, 2, figsize=(15, 12))
            fig.suptitle('地区分布分析', fontsize=16, fontweight='bold')

            # 省份分布TOP10
            province_counts = self.data_service.region_data['省份'].value_counts().head(10)
            ax1.bar(province_counts.index, province_counts.values, color='skyblue')
            ax1.set_title('省份覆盖TOP10')
            ax1.set_ylabel('地区数量')
            plt.setp(ax1.xaxis.get_majorticklabels(), rotation=45)

            # 城市分布TOP10
            city_counts = self.data_service.region_data['城市'].value_counts().head(10)
            ax2.barh(city_counts.index, city_counts.values, color='lightgreen')
            ax2.set_title('城市覆盖TOP10')
            ax2.set_xlabel('地区数量')

            # 经纬度分布散点图
            ax3.scatter(self.data_service.region_data['经度'], self.data_service.region_data['纬度'],
                       alpha=0.6, color='red', s=10)
            ax3.set_title('地理位置分布')
            ax3.set_xlabel('经度')
            ax3.set_ylabel('纬度')

            # 省份简称分布
            province_short_counts = self.data_service.region_data['省份简称'].value_counts().head(15)
            ax4.pie(province_short_counts.values, labels=province_short_counts.index, autopct='%1.1f%%')
            ax4.set_title('省份分布占比')

            plt.tight_layout()
            return self.plot_to_base64(fig)

        except Exception as e:
            print(f"地区分析图表生成失败: {e}")
            return None

    def create_time_analysis_chart(self):
        """创建时间分析图表"""
        try:
            if self.data_service.time_data.empty or self.data_service.order_data.empty:
                return None

            # 合并订单和时间数据
            merged_data = self.data_service.order_data.merge(
                self.data_service.time_data, on='时间ID', how='left'
            )

            fig, ((ax1, ax2), (ax3, ax4)) = plt.subplots(2, 2, figsize=(15, 12))
            fig.suptitle('时间趋势分析', fontsize=16, fontweight='bold')

            # 星期分布
            if '星期' in merged_data.columns:
                weekday_counts = merged_data['星期'].value_counts()
                weekday_order = ['星期一', '星期二', '星期三', '星期四', '星期五', '星期六', '星期日']
                weekday_counts = weekday_counts.reindex(weekday_order, fill_value=0)
                ax1.bar(weekday_counts.index, weekday_counts.values, color='lightblue')
                ax1.set_title('星期订单分布')
                ax1.set_ylabel('订单数量')
                plt.setp(ax1.xaxis.get_majorticklabels(), rotation=45)

            # 月份分布
            if '年月' in merged_data.columns:
                month_counts = merged_data['年月'].value_counts().sort_index()
                ax2.plot(month_counts.index, month_counts.values, marker='o', color='green')
                ax2.set_title('月份订单趋势')
                ax2.set_ylabel('订单数量')
                ax2.set_xlabel('年月')
                plt.setp(ax2.xaxis.get_majorticklabels(), rotation=45)

            # 开始时间分布（小时）
            if '开始时间' in merged_data.columns:
                # 提取小时
                start_hours = merged_data['开始时间'].str.split(':').str[0]
                start_hours = pd.to_numeric(start_hours, errors='coerce').dropna()
                hour_counts = start_hours.value_counts().sort_index()
                ax3.bar(hour_counts.index, hour_counts.values, color='orange')
                ax3.set_title('开始时间分布（按小时）')
                ax3.set_xlabel('小时')
                ax3.set_ylabel('订单数量')

            # 年内天数分布
            if '年内天数' in merged_data.columns:
                day_counts = merged_data['年内天数'].value_counts().sort_index()
                ax4.plot(day_counts.index, day_counts.values, color='red', alpha=0.7)
                ax4.set_title('年内天数订单分布')
                ax4.set_xlabel('年内第几天')
                ax4.set_ylabel('订单数量')

            plt.tight_layout()
            return self.plot_to_base64(fig)

        except Exception as e:
            print(f"时间分析图表生成失败: {e}")
            return None

    def create_comprehensive_dashboard(self):
        """创建综合仪表板"""
        try:
            if self.data_service.order_data.empty:
                return None

            fig, ((ax1, ax2, ax3), (ax4, ax5, ax6)) = plt.subplots(2, 3, figsize=(20, 12))
            fig.suptitle('共享充电宝数据综合仪表板', fontsize=18, fontweight='bold')

            # 1. 品牌市场份额
            brand_counts = self.data_service.order_data['品牌'].value_counts()
            ax1.pie(brand_counts.values, labels=brand_counts.index, autopct='%1.1f%%')
            ax1.set_title('品牌市场份额')

            # 2. 单价分布
            ax2.hist(self.data_service.order_data['单价'], bins=10, color='skyblue', alpha=0.7)
            ax2.set_title('单价分布')
            ax2.set_xlabel('单价(元)')
            ax2.set_ylabel('订单数量')

            # 3. 品牌平均单价
            brand_price = self.data_service.order_data.groupby('品牌')['单价'].mean().sort_values(ascending=False)
            ax3.bar(brand_price.index, brand_price.values, color='lightgreen')
            ax3.set_title('品牌平均单价')
            ax3.set_ylabel('单价(元)')
            plt.setp(ax3.xaxis.get_majorticklabels(), rotation=45)

            # 4. 用户年龄分布
            if not self.data_service.user_data.empty:
                age_bins = [0, 20, 30, 40, 50, 60, 100]
                age_labels = ['<20', '20-30', '30-40', '40-50', '50-60', '60+']
                age_groups = pd.cut(self.data_service.user_data['年龄'], bins=age_bins, labels=age_labels)
                age_counts = age_groups.value_counts()
                ax4.bar(age_counts.index, age_counts.values, color='orange')
                ax4.set_title('用户年龄分布')
                ax4.set_ylabel('用户数量')

            # 5. 省份分布TOP10
            if not self.data_service.region_data.empty:
                province_counts = self.data_service.region_data['省份'].value_counts().head(10)
                ax5.barh(province_counts.index, province_counts.values, color='pink')
                ax5.set_title('省份覆盖TOP10')
                ax5.set_xlabel('地区数量')

            # 6. 品牌收入分析
            brand_revenue = self.data_service.order_data.groupby('品牌')['单价'].sum().sort_values(ascending=False)
            ax6.bar(brand_revenue.index, brand_revenue.values, color='purple', alpha=0.7)
            ax6.set_title('品牌总收入')
            ax6.set_ylabel('收入(元)')
            plt.setp(ax6.xaxis.get_majorticklabels(), rotation=45)

            plt.tight_layout()
            return self.plot_to_base64(fig)

        except Exception as e:
            print(f"综合仪表板生成失败: {e}")
            return None

# 初始化服务
data_service = DataAnalysisService()
ai_service = AIAnalysisService(data_service)
viz_service = VisualizationService(data_service)

# API路由
@app.route('/')
def index():
    """API首页"""
    return jsonify({
        'message': '共享充电宝数据仓库AI分析API',
        'version': '1.0.0',
        'endpoints': {
            'data_summary': '/api/data/summary',
            'ai_chat': '/api/ai/chat',
            'ai_analysis': {
                'user_behavior': '/api/ai/analyze-users',
                'market_trend': '/api/ai/analyze-market',
                'regional_distribution': '/api/ai/analyze-regions',
                'revenue_optimization': '/api/ai/analyze-revenue'
            },
            'visualizations': {
                'brand_chart': '/api/viz/brand-analysis',
                'user_chart': '/api/viz/user-analysis',
                'region_chart': '/api/viz/region-analysis',
                'time_chart': '/api/viz/time-analysis',
                'dashboard': '/api/viz/dashboard'
            }
        }
    })

@app.route('/api/data/summary')
def get_data_summary():
    """获取数据概览"""
    try:
        summary = data_service.get_data_summary()
        return jsonify({
            'success': True,
            'data': summary
        })
    except Exception as e:
        return jsonify({
            'success': False,
            'error': str(e)
        }), 500

@app.route('/api/ai/chat', methods=['POST'])
def ai_chat():
    """AI智能问答"""
    try:
        data = request.get_json()
        question = data.get('question', '')

        if not question:
            return jsonify({
                'success': False,
                'error': '请输入问题'
            }), 400

        analysis = ai_service.chat_analysis(question)
        return jsonify({
            'success': True,
            'analysis': analysis,
            'type': 'chat',
            'question': question
        })
    except Exception as e:
        return jsonify({
            'success': False,
            'error': str(e)
        }), 500

@app.route('/api/ai/analyze-users', methods=['POST'])
def analyze_user_behavior():
    """用户行为分析"""
    try:
        analysis = ai_service.analyze_user_behavior()
        return jsonify({
            'success': True,
            'analysis': analysis,
            'type': 'user_behavior'
        })
    except Exception as e:
        return jsonify({
            'success': False,
            'error': str(e)
        }), 500

@app.route('/api/ai/analyze-market', methods=['POST'])
def analyze_market_trend():
    """市场趋势分析"""
    try:
        analysis = ai_service.analyze_market_trend()
        return jsonify({
            'success': True,
            'analysis': analysis,
            'type': 'market_trend'
        })
    except Exception as e:
        return jsonify({
            'success': False,
            'error': str(e)
        }), 500

@app.route('/api/ai/analyze-regions', methods=['POST'])
def analyze_regional_distribution():
    """区域分布分析"""
    try:
        analysis = ai_service.analyze_regional_distribution()
        return jsonify({
            'success': True,
            'analysis': analysis,
            'type': 'regional_distribution'
        })
    except Exception as e:
        return jsonify({
            'success': False,
            'error': str(e)
        }), 500

@app.route('/api/ai/analyze-revenue', methods=['POST'])
def analyze_revenue_optimization():
    """收入优化分析"""
    try:
        analysis = ai_service.analyze_revenue_optimization()
        return jsonify({
            'success': True,
            'analysis': analysis,
            'type': 'revenue_optimization'
        })
    except Exception as e:
        return jsonify({
            'success': False,
            'error': str(e)
        }), 500

@app.route('/api/viz/brand-analysis')
def get_brand_analysis_chart():
    """获取品牌分析图表"""
    try:
        chart_data = viz_service.create_brand_analysis_chart()
        if chart_data:
            return jsonify({
                'success': True,
                'chart': chart_data,
                'type': 'brand_analysis'
            })
        else:
            return jsonify({
                'success': False,
                'error': '图表生成失败'
            }), 500
    except Exception as e:
        return jsonify({
            'success': False,
            'error': str(e)
        }), 500

@app.route('/api/viz/user-analysis')
def get_user_analysis_chart():
    """获取用户分析图表"""
    try:
        chart_data = viz_service.create_user_analysis_chart()
        if chart_data:
            return jsonify({
                'success': True,
                'chart': chart_data,
                'type': 'user_analysis'
            })
        else:
            return jsonify({
                'success': False,
                'error': '图表生成失败'
            }), 500
    except Exception as e:
        return jsonify({
            'success': False,
            'error': str(e)
        }), 500

@app.route('/api/viz/region-analysis')
def get_region_analysis_chart():
    """获取地区分析图表"""
    try:
        chart_data = viz_service.create_region_analysis_chart()
        if chart_data:
            return jsonify({
                'success': True,
                'chart': chart_data,
                'type': 'region_analysis'
            })
        else:
            return jsonify({
                'success': False,
                'error': '图表生成失败'
            }), 500
    except Exception as e:
        return jsonify({
            'success': False,
            'error': str(e)
        }), 500

@app.route('/api/viz/time-analysis')
def get_time_analysis_chart():
    """获取时间分析图表"""
    try:
        chart_data = viz_service.create_time_analysis_chart()
        if chart_data:
            return jsonify({
                'success': True,
                'chart': chart_data,
                'type': 'time_analysis'
            })
        else:
            return jsonify({
                'success': False,
                'error': '图表生成失败'
            }), 500
    except Exception as e:
        return jsonify({
            'success': False,
            'error': str(e)
        }), 500

@app.route('/api/viz/dashboard')
def get_comprehensive_dashboard():
    """获取综合仪表板"""
    try:
        chart_data = viz_service.create_comprehensive_dashboard()
        if chart_data:
            return jsonify({
                'success': True,
                'chart': chart_data,
                'type': 'dashboard'
            })
        else:
            return jsonify({
                'success': False,
                'error': '仪表板生成失败'
            }), 500
    except Exception as e:
        return jsonify({
            'success': False,
            'error': str(e)
        }), 500

if __name__ == '__main__':
    print("🚀 共享充电宝数据仓库AI分析API服务启动中...")
    print(f"📁 数据路径: {DATA_PATH}")
    print("🌐 服务地址: http://localhost:5000")
    print("📖 API文档: http://localhost:5000")

    app.run(debug=True, host='0.0.0.0', port=5000)